﻿goog.provide('imc.ui.UserPage');
//goog.inherits(imc.ui.UserPage, imc.ui.Page);

imc.ui.UserPage = function (opt) { //Constructor
    //attributes privados
    var dataGrid;

    /*\\Behavior : --------------------------------- */
    //Todos los ids van con #
    this.opt = {
        idDivContent: "#der"
        , idDivNav: "#izq"
        , idTableDataTable: "#tblDatosUsuarios"
        , uriSrvGetDataListUser: "Services/User.svc/GetDataListUser"
        , uriSrvDeleteUser: "Services/User.svc/DeleteUser"
        , uriSrvInsertUser: "Services/User.svc/InsertUser"
        , uriSrvUpdateUser: "Services/User.svc/UpdateUser"
        , uriSrvGetOneUser: "Services/User.svc/GetOneUser"
    };

    $().extend(this.opt, opt);
    //alert(this.opt.test);
    this.draw();
    /*//Behavior : --------------------------------- */
} //Fin constructor

//Atributos Público************************************************
imc.ui.UserPage.prototype.opt = null;

//Metodos Públicos*************************************************
imc.ui.UserPage.prototype.draw = function () {
    $(this.opt.idDivNav).load('userPage.html #navigationPanelUsuarios', function () { });
    this.loadContent();
};

imc.ui.UserPage.prototype.loadContent = function () {
    var that = this;
    $(this.opt.idDivContent).load('userPage.html #contentUsers', function () {
        that.userDataTable();
    });
};

imc.ui.UserPage.prototype.userDataTable = function () {
    var that = this;
    $.ajax({
        url: this.opt.uriSrvGetDataListUser
        , type: "POST"
        , dataType: "json"
        , data: '{}'
        , contentType: "application/json; charset=utf-8"
        , success: function (data) {
            var oTableTblUsuarios = $('#tblDatosUsuarios').dataTable({
                'bInfo': false
                ,'bPaginate': false
                ,'bLengthChange': false
                ,'bRetrieve': true, 'sDom': ''
                ,'sInfoEmpty': ''
                ,'bAutoWidth': false
                ,aaData: data.GetDataListUserResult
                ,aoColumns: [
                    {
                        "aTargets": [0]
                        , "fnRender": function (oObj) {
                        return '<input type="checkbox" id="readonly" imc-data="' + oObj.aData["ID_USER"] + '" value="' + oObj.aData[0] + '" name="check" />';
                    }
                        , "sClass": "checkboxId"
                        , "bSearchable": false
                        , "bSortable": false
                        , "mDataProp": "check"
                        , "sWidth": "4%"
                    }
                    , { "sTitle": "Nombre", "mDataProp": "USER_NAME", "sClass": "editarUsuario" }
                    , { "sTitle": "Mail", "mDataProp": "USER_MAIL", "sClass": "editarUsuario" }
                    , { "sTitle": "Default Page", "mDataProp": "DEFAULT_PAGE", "sClass": "editarUsuario" }
                ]
            });
            $('#tblDatosUsuarios tbody .editarUsuario').die('click');
            $('#tblDatosUsuarios tbody .editarUsuario').live('click', function () {
                /*var tt = $(this).parent();
                 for (var t in this) {
                 console.log(t);
                 }*/
                var oTableTblUsuarios = $('#tblDatosUsuarios').dataTable();
                var sDataUsuario = oTableTblUsuarios.fnGetData($(this).parent().get(0));
                console.log(sDataUsuario);
                for (var i in sDataUsuario) {
                    if (i = 'ID_USER') {
                        idUser = sDataUsuario[i];
                    }
                }
                var dlg = that.dlgUpdateUser(idUser);
                dlg.setVisible(true);
                /*\\TabPane Users : -----------------------------*/
                var tabPane = new goog.ui.TabPane(document.getElementById('tabPane'));
                tabPane.addPage(new goog.ui.TabPane.TabPage(document.getElementById('tabInfoUser'), 'Información'));
                tabPane.addPage(new goog.ui.TabPane.TabPage(document.getElementById('tabRolesUser'), 'Roles'));
                tabPane.addPage(new goog.ui.TabPane.TabPage(document.getElementById('tabSeguridadUser'), 'Seguridad'));
                /*//TabPane Users : -----------------------------*/
                /*\\Recuperar campos para modificar--------------*/
                $.ajax({
                    type: "POST"
                    , url: that.opt.uriSrvGetOneUser
                    , data: '{"ID_USER":' + idUser + '}'
                    , contentType: "application/json; charset=utf-8"
                    , dataType: "json"
                    , success: function (data) {
                        console.log(data.GetOneUserResult);
                        if (data.GetOneUserResult != null) {
                            /*\\Object CharCounter : ------------------------*/
                            var userCharCounter = new imc.CharCounter({columnName:'user'});
                            /*//Object CharCounter : ------------------------*/
                            document.getElementById('USER_NAME').value = data.GetOneUserResult["USER_NAME"];
                            document.getElementById('USER_MAIL').value = data.GetOneUserResult["USER_MAIL"];
                            document.getElementById('PASSWORD').value = data.GetOneUserResult["PASSWORD"];
                            document.getElementById('confirmPass').value = data.GetOneUserResult["PASSWORD"];
                            document.getElementById('DEFAULT_PAGE').value = data.GetOneUserResult["DEFAULT_PAGE"];
                        } else {
                            alert('Los datos vienen vacios ({"GetOneUserResult":null})');
                        }
                    }
                    , error: function (result) {
                        alert('Error al recuperar usuarios ' + result.status + ' ' + result.statusText);
                    }
                });
                /*//Recuperar campos para modificar--------------*/
                /*\\DataTable Roles : ---------------------------*/
                $.ajax({
                    url: "Services/User.svc/GetListRolChecked"
                    ,type: "POST"
                    ,dataType: "json"
                    ,data: '{"ID_USER":"' + idUser + '"}'
                    ,contentType: "application/json; charset=utf-8"
                    ,success: function (data) {
                        oTableTblRoles = $('#dataTableUserRoles').dataTable({
                            'bInfo': false,
                            'bPaginate': false,
                            'bLengthChange': false,
                            'bRetrieve': true, 'sDom': '',
                            'sInfoEmpty': '',
                            aaData: data.GetListRolCheckedResult,
                            aoColumns: [
                                { "mDataProp": "ROL_NAME"},
                                {
                                    "aTargets": [0],
                                    "fnRender": function (oObj) {
                                        return '<input type="checkbox"' + ((oObj.aData["CHECKED"] == '1') ? 'checked="true"' : '') +'id="readonly" imc-data="' + oObj.aData["ID_ROL"] + '" value="' + oObj.aData[0] + '" name="check"/>';
                                    },
                                    "sClass": "checkboxId",
                                    "bSearchable": false,
                                    "bSortable": false,
                                    "mDataProp": "CHECKED",
                                    "sWidth": "4%"
                                }
                            ]
                        });
                    },
                    error: function (result) {
                        alert('Error al mostrar el grid roles ' + result.status + ' ' + result.statusText);
                    }
                });
                /*//DataTable Roles : --------------------------*/
            });
            $('#nuevoUsuario').die('click');
            $('#nuevoUsuario').click(function () {
                var dlg = that.dlgNewUser({test: function(check){
                    console.log('como parámetro: '+check);
                    $.ajax({
                        type: "POST"
                        ,url: that.opt.uriSrvGetDataListUser
                        ,data: '{}'
                        ,contentType: "application/json; charset=utf-8"
                        ,dataType: "json"
                        ,success: function (data) {
                            var idNewUser;
                            var ot = $("#tblDatosUsuarios").dataTable();
                            ot.fnClearTable();
                            ot.fnAddData(data.GetDataListUserResult);
                            for (var i = 0; i < data.GetDataListUserResult.length; i++) {
                                idNewUser = data.GetDataListUserResult[i].ID_USER;
                            }
                            console.log(idNewUser + check);
                            $.ajax({
                                url: "Services/User.svc/insertRelUserRol"
                                , type: "POST"
                                , dataType: "json"
                                , data: '{"ID_USER":' + idNewUser + ',"ROLES":"' + that.opt.check + '"}'
                                , contentType: "application/json; charset=utf-8"
                                , success: function (data){
                                    console.log('Relación creada');
                                }
                                , error: function (result) {
                                    console.log('Error al crear la relación ' + result.status + ' ' + result.statusText);
                                }
                            });
                        }
                        ,error: function (result) {
                            alert('Error al recargar la tabla de usuarios' + result.status + ' ' + result.statusText);
                        }
                    });}
                });
                dlg.setVisible(true);
                /*\\TabPane Users : -----------------------------*/
                var tabPane = new goog.ui.TabPane(document.getElementById('tabPane'));
                tabPane.addPage(new goog.ui.TabPane.TabPage(document.getElementById('tabInfoUser'), 'Información'));
                tabPane.addPage(new goog.ui.TabPane.TabPage(document.getElementById('tabRolesUser'), 'Roles'));
                tabPane.addPage(new goog.ui.TabPane.TabPage(document.getElementById('tabSeguridadUser'), 'Seguridad'));
                /*//TabPane Users : -----------------------------*/
                /*\\Object CharCounter : ------------------------*/
                var userCharCounter = new imc.CharCounter({columnName:"USER"});
                /*//Object CharCounter : ------------------------*/
            });
            $('#eliminarUsuario').die('click');
            $('#eliminarUsuario').click(function () {
                var oTableTblUsuarios = $('#tblDatosUsuarios').dataTable();
                var stringDeleteUser = "";
                $('input[type="checkbox"]:checked', oTableTblUsuarios.fnGetNodes()).each(function (i) {
                    stringDeleteUser += $(this).attr("imc-data") + ",";
                });
                if (stringDeleteUser != "") {
                    stringDeleteUser = stringDeleteUser.substring(0, stringDeleteUser.length - 1);
                }
                if (stringDeleteUser != "") {
                    var dlg = that.dlgDeleteUser(stringDeleteUser);
                    dlg.setVisible(true);
                } else {
                    alert('No hay ningún usuario seleccionado');
                    return true;
                }
            });
        }
        , error: function (result) {
            alert('Error al mostrar el grid usuarios ' + result.status + ' ' + result.statusText);
        }
    });
};

imc.ui.UserPage.prototype.reloadUserDataTable = function () { //Recargar tabla al modificar o eliminar usuario
    var that = this;
    $.ajax({
        type: "POST"
        ,url: this.opt.uriSrvGetDataListUser
        ,data: '{}'
        ,contentType: "application/json; charset=utf-8"
        ,dataType: "json"
        ,success: function (data) {
            var ot = $("#tblDatosUsuarios").dataTable();
            ot.fnClearTable();
            ot.fnAddData(data.GetDataListUserResult);
        }
        ,error: function (result) {
            alert('Error al recargar la tabla de usuarios' + result.status + ' ' + result.statusText);
        }
    });
}; //Fin recargar tabla al agregar, modificar o eliminar usuario

imc.ui.UserPage.prototype.dlgNewUser = function (opt) { //Dialog agregar usuario
    var that = this;
    $().extend(this.opt, opt);
    //this.opt.test;
    this.dialogAgregarUsuario = new goog.ui.Dialog();
    this.dialogAgregarUsuario.setContent(
        /*\\TabPane dlg newUser : -----------------------------------*/
        '<div id="tabPane"></div><br/>'
        /*//TabPane dlg newUser : -----------------------------------*/
        /*\\Información de nuevo usuario : --------------------------*/
        +'<div id="tabInfoUser"style="font-size: 85%";>'
            +'<div class="validateUser"><label class="validarUsuario"></label></div><br/>'
            +'<div><div style="width:150px; float:left;"><label style="float:right;">Nombre: </label></div><div style="width:450px; float:left;"><input type="text" id="USER_NAME" style="width: 250px;" /></div></div><br /><br />'
            +'<div><div style="width:150px; float:left;"><label style="float:right;">Mail: </label></div><div style="width:450px; float:left;"><input type="text" id="USER_MAIL" style="width: 250px;" /></div></div><br /><br />'
            +'<div><div style="width:150px; float:left;"><label style="float:right;">Password: </label></div><div style="width:450px; float:left;"><input type="password" id="PASSWORD" style="width: 250px;" /></div></div><br /><br />'
            +'<div><div style="width:150px; float:left;"><label style="float:right;">Confirmar password: </label></div><div style="width:450px; float:left;"><input type="password" id="confirmPass" style="width: 250px;" /></div></div><br /><br />'
            +'<div><div style="width:150px; float:left;"><label style="float:right;">Default page: </label></div><div style="width:450px; float:left;"><input type="text" id="DEFAULT_PAGE" style="width: 250px;" /></div></div>'
        +'</div>'
        /*//Información de nuevo usuario : --------------------------*/
       /*\\Roles de nuevo usuario : ---------------------------------*/
        +'<div style="font-size: 85%;" id="tabRolesUser">'
            +'<div class="validateUser"><label class="validarUsuario"></label></div><br/>'
                +'<table cellpadding="0" cellspacing="0" border="0" class="display" id="dataTableUserRoles" style="width:340px;"></table>'
        +'</div>'
        /*//Roles de nuevo usuario : ---------------------------------*/
        /*\\Seguridad de nuevo usuario : -----------------------------*/
        +'<div style="font-size: 85%;" id="tabSeguridadUser">'
            +'<div class="validateUser"><label class="validarUsuario"></label></div><br/>'
            +'<label>Seguridad</label>'
        +'</div>'
        /*//Seguridad de nuevo usuario : -----------------------------*/
    );
    var titleAgregarUsuario = goog.dom.createDom("p", { style: 'margin:0;padding:0;color:black;font-size:80%;' }, 'Agregar Usuario');
    this.dialogAgregarUsuario.setTitle(titleAgregarUsuario);
    var btnAgregarUsuario = new goog.ui.Dialog.ButtonSet();
    btnAgregarUsuario.addButton({ caption: "Agregar", key: "e" }).addButton({ caption: "Cancelar", key: "o" });
    this.dialogAgregarUsuario.setButtonSet(btnAgregarUsuario);
    this.dialogAgregarUsuario.setDisposeOnHide(true);
    /*\\DataTable Roles : ---------------------------*/
    $.ajax({
        url: "Services/User.svc/GetDataListRol"
        ,type: "POST"
        ,dataType: "json"
        ,data: '{}'
        ,contentType: "application/json; charset=utf-8"
        ,success: function (data) {
            oTableTblRoles = $('#dataTableUserRoles').dataTable({
                'bInfo': false,
                'bPaginate': false,
                'bLengthChange': false,
                'bRetrieve': true, 'sDom': '',
                'sInfoEmpty': '',
                aaData: data.GetDataListRolResult,
                aoColumns: [
                    { "mDataProp": "ROL_NAME"},
                    {
                        "aTargets": [0],
                        "fnRender": function (oObj) {
                            return '<input type="checkbox" id="readonly" imc-data="' + oObj.aData["ID_ROL"] + '" value="' + oObj.aData[0] + '" name="check" />';
                        },
                        "sClass": "checkboxId",
                        "bSearchable": false,
                        "bSortable": false,
                        "mDataProp": "check"
                    }
                ]
            });
        },
        error: function (result) {
            alert('Error al mostrar el grid roles ' + result.status + ' ' + result.statusText);
        }
    });
    /*//DataTable Roles : --------------------------*/
    goog.events.listen(this.dialogAgregarUsuario, goog.ui.Dialog.EventType.SELECT, function (e) {
        if (e.key == "o") {
            return true;
        } else {
            var val2 = $("#USER_NAME").val();
            var val3 = $("#USER_MAIL").val();
            var val4 = $("#PASSWORD").val();
            var val5 = $("#DEFAULT_PAGE").val();
            var pass = $("#confirmPass").val();
            var check = "";
            var uncheck = "";
            var oTable = $('#dataTableUserRoles').dataTable();
            $('input', oTable.fnGetNodes()).each(function (i) {
                if ($(this).is(':checked')) {
                    check += "{ID_ROL:"  + "'" + $(this).attr("imc-data") + "'" + ",CHECKED:'1'},";
                    uncheck += 1;
            }
                else {
                    //check += "'" + $(this).attr("imc-data") + "'" + ":'0',";
                    uncheck += 0;
                }
            });
            console.log('check antes del substring: '+check);
            if (check != "") {
                check = check.substring(0, check.length - 1);
            }
            console.log('check después del substring: '+check);
            that.opt.check = '[' + check + ']';
            console.log('check con corchetes: '+check);

            if (val2 == "" || val3 == "" || val4 == "" || val5 == "" || pass == "") {
                $('.validarUsuario').css({ color: "Red" });
                $('.validarUsuario').html('Todos los campos de información son requeridos');
                return false;
            }
            else if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(val3)) {
                $("#USER_MAIL").css({ background: "#FFFF66" });
                $("#USER_MAIL").css({ color: "red" });
                $("#PASSWORD").css({ background: "white" });
                $("#confirmPass").css({ background: "white" });
                $("#PASSWORD").css({ color: "black" });
                $("#confirmPass").css({ color: "black" });
                $('.validarUsuario').css({ color: "Red" });
                $('.validarUsuario').html('Ingrese un correo valido');
                return false;
            }
            else if (val4 != pass) {
                $("#USER_MAIL").css({ background: "white" });
                $("#USER_MAIL").css({ color: "black" });
                $("#PASSWORD").css({ background: "#FFFF66" });
                $("#confirmPass").css({ background: "#FFFF66" });
                $("#PASSWORD").css({ color: "Red" });
                $("#confirmPass").css({ color: "Red" });
                $('.validarUsuario').css({ color: "Red" });
                $('.validarUsuario').html('Los password no coinciden');
                return false;
            }
            else if(uncheck == 0){
                $("#USER_MAIL").css({ background: "white" });
                $("#USER_MAIL").css({ color: "black" });
                $("#PASSWORD").css({ background: "white" });
                $("#confirmPass").css({ background: "white" });
                $("#PASSWORD").css({ color: "black" });
                $("#confirmPass").css({ color: "black" });
                $('.validarUsuario').css({ color: "Red" });
                $('.validarUsuario').html('Seleccione al menos un Rol');
                return false;
            } else {
                $.ajax({
                    type: "POST"
                    ,url: that.opt.uriSrvInsertUser
                    ,data: '{"USER_NAME":"' + val2 + '","USER_MAIL":"' + val3 + '","PASSWORD":"' + val4 + '","DEFAULT_PAGE":"' + val5 + '"}'
                    ,contentType: "application/json; charset=utf-8"
                    ,dataType: "json"
                    ,success: function (data) {
                        var test = "";
                        test = data.InsertUserResult.state;
                        console.log('state: '+test);
                        if(!test){
                            console.log("entro dlgNuevo") ;
                            $("#USER_MAIL").css({ background: "#FFFF66" });
                            $("#USER_MAIL").css({ color: "red" });
                            $("#PASSWORD").css({ background: "white" });
                            $("#confirmPass").css({ background: "white" });
                            $("#PASSWORD").css({ color: "black" });
                            $("#confirmPass").css({ color: "black" });
                            $('.validarUsuario').css({ color: "Red" });
                            $('.validarUsuario').html('Ya existe un usuario con esta cuenta de correo');
                            return null;
                        } else {
                            that.opt.test(check);
                            that.dialogAgregarUsuario.setVisible(false);
                        }
                    }
                    ,error: function (result) {
                        alert('Error al agregar usuario ' + result.status + ' ' + result.statusText);
                    }
                });
                return false;
            }
        }
    });
    return this.dialogAgregarUsuario;
}; //Fin dialog agregar usuario

imc.ui.UserPage.prototype.dlgDeleteUser = function (stringDeleteUser) { //Dialog borrar usuarios
    var that = this;
    this.dialogBorrarUsuario = new goog.ui.Dialog();
    this.dialogBorrarUsuario.setContent(
        '<div style="font-size: 85%;">'
            +'<label>¿Está seguro que desea eliminar los Usuarios seleccionados?</label><br />'
        +'</div>'
    );
    this.dialogBorrarUsuario.setTitle('Borrar Usuario');
    var btnBorrarUsuario = new goog.ui.Dialog.ButtonSet();
    btnBorrarUsuario.addButton({ caption: "Borrar", key: "e" }).addButton({ caption: "Cancelar", key: "o" });
    this.dialogBorrarUsuario.setButtonSet(btnBorrarUsuario);
    this.dialogBorrarUsuario.setDisposeOnHide(true);
    goog.events.listen(this.dialogBorrarUsuario, goog.ui.Dialog.EventType.SELECT, function (e) {
        if (e.key == "o") {
            return true;
        } else {
            console.log(stringDeleteUser);
            $.ajax({
                url: that.opt.uriSrvDeleteUser
                ,type: "POST"
                ,dataType: "json"
                ,data: '{"ID_USER": "' + stringDeleteUser + '" }'
                ,contentType: "application/json; charset=utf-8"
                ,success: function (data) {
                    if (data) {
                        that.reloadUserDataTable();
                        return true;
                    }
                }
                ,error: function (result) {
                    alert('Error al borrar usuarios ' + result.status + ' ' + result.statusText);
                }
            });
        }
    });
    return this.dialogBorrarUsuario;
} //Fin dialog borrar usuarios
   
imc.ui.UserPage.prototype.dlgUpdateUser = function (idUser) { //Dialog modificar usuario
    var that = this;
    this.dialogModificarUsuario = new goog.ui.Dialog();
    this.dialogModificarUsuario.setContent(
    /*\\TabPane dlg updateUser : -----------------------------------*/
    '<div id="tabPane"></div><br/>'
        /*//TabPane dlg updateUser : -----------------------------------*/
        /*\\Información de modificar usuario : --------------------------*/
        +'<div id="tabInfoUser"style="font-size: 85%";>'
            +'<div class="validateUser"><label class="validarUsuario"></label></div><br/>'
            +'<div><div style="width:150px; float:left;"><label style="float:right;">Nombre: </label></div><div style="width:450px; float:left;"><input type="text" id="USER_NAME" style="width: 250px;" /></div></div><br /><br />'
            +'<div><div style="width:150px; float:left;"><label style="float:right;">Mail: </label></div><div style="width:450px; float:left;"><input type="text" id="USER_MAIL" style="width: 250px;" /></div></div><br /><br />'
            +'<div><div style="width:150px; float:left;"><label style="float:right;">Password: </label></div><div style="width:450px; float:left;"><input type="password" id="PASSWORD" style="width: 250px;" /></div></div><br /><br />'
            +'<div><div style="width:150px; float:left;"><label style="float:right;">Confirmar password: </label></div><div style="width:450px; float:left;"><input type="password" id="confirmPass" style="width: 250px;" /></div></div><br /><br />'
            +'<div><div style="width:150px; float:left;"><label style="float:right;">Default page: </label></div><div style="width:450px; float:left;"><input type="text" id="DEFAULT_PAGE" style="width: 250px;" /></div></div>'
        +'</div>'
        /*//Información de modificar usuario : --------------------------*/
        /*\\Roles de modificar usuario : ---------------------------------*/
        +'<div style="font-size: 85%;" id="tabRolesUser">'
            +'<div class="validateUser"><label class="validarUsuario"></label></div><br/>'
            +'<table cellpadding="0" cellspacing="0" border="0" class="display" id="dataTableUserRoles" style="width:340px;"></table>'
        +'</div>'
        /*//Roles de modificar usuario : ---------------------------------*/
        /*\\Seguridad de modificar usuario : -----------------------------*/
        +'<div style="font-size: 85%;" id="tabSeguridadUser">'
            +'<div class="validateUser"><label class="validarUsuario"></label></div><br/>'
            +'<label>Seguridad</label>'
        +'</div>'
        /*//Seguridad de modificar usuario : -----------------------------*/
    );
    var titleModificarUsuario = goog.dom.createDom("p", { style: 'margin:0;padding:0;color:black;font-size:80%;' }, 'Modificar Usuario');
    this.dialogModificarUsuario.setTitle(titleModificarUsuario);
    var btnModificarUsuario = new goog.ui.Dialog.ButtonSet();
    btnModificarUsuario.addButton({ caption: "Guardar cambios", key: "e" }).addButton({ caption: "Cancelar", key: "o" });
    this.dialogModificarUsuario.setButtonSet(btnModificarUsuario);
    this.dialogModificarUsuario.setDisposeOnHide(true);
    goog.events.listen(this.dialogModificarUsuario, goog.ui.Dialog.EventType.SELECT, function (e) {
//alert(e.key);
        if (e.key == "o") {
            return true;
        } else {
            var val2 = $("#USER_NAME").val();
            var val3 = $("#USER_MAIL").val();
            var val4 = $("#PASSWORD").val();
            var pass = $("#confirmPass").val();
            var val5 = $("#DEFAULT_PAGE").val();
            var check = "";
            var uncheck = "";
            var oTable = $('#dataTableUserRoles').dataTable();
            $('input', oTable.fnGetNodes()).each(function (i) {
                if ($(this).is(':checked')) {
                    check += "{ID_ROL:"  + "'" + $(this).attr("imc-data") + "'" + ",CHECKED:'1'},";
                    uncheck += 1;
                }
                else {
                    //check += "'" + $(this).attr("imc-data") + "'" + ":'0',";
                    uncheck += 0;
                }
            });
            if (check != "") {
                check = check.substring(0, check.length - 1);
            }
            check = '[' + check + ']';
            console.log(check);
            if (val2 == "" || val3 == "" || val4 == "" || val5 == "") {
                $('.validarUsuario').css({ color: "Red" });
                $('.validarUsuario').html('Todos los campos son requeridos');
                return false;
            }
            else if (val4 != pass) {
                $("#PASSWORD").css({ background: "#FFFF66" });
                $("#confirmPass").css({ background: "#FFFF66" });
                $("#PASSWORD").css({ color: "Red" });
                $("#confirmPass").css({ color: "Red" });
                $('.validarUsuario').css({ color: "Red" });
                $('.validarUsuario').html('Los password no coinciden');
                return false;
            }
            else if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(val3)) {
                $("#USER_MAIL").css({ background: "#FFFF66" });
                $("#USER_MAIL").css({ color: "red" });
                $("#PASSWORD").css({ background: "white" });
                $("#confirmPass").css({ background: "white" });
                $("#PASSWORD").css({ color: "black" });
                $("#confirmPass").css({ color: "black" });
                $('.validarUsuario').css({ color: "Red" });
                $('.validarUsuario').html('Ingrese un correo valido');
                return false;
            }
            else if(uncheck == 0){
                    $("#USER_MAIL").css({ background: "white" });
                    $("#USER_MAIL").css({ color: "black" });
                    $("#PASSWORD").css({ background: "white" });
                    $("#confirmPass").css({ background: "white" });
                    $("#PASSWORD").css({ color: "black" });
                    $("#confirmPass").css({ color: "black" });
                    $('.validarUsuario').css({ color: "Red" });
                    $('.validarUsuario').html('Seleccione al menos un Rol');
                    return false;
            } else {
                $.ajax({
                    url: that.opt.uriSrvUpdateUser
                    ,type: "POST"
                    ,data:
                        '{"ID_USER":' + idUser
                        + ',"USER_NAME":"' + val2
                        + '","USER_MAIL":"' + val3
                        + '","PASSWORD":"' + val4
                        + '","DEFAULT_PAGE":"' + val5 + '"}'
                    ,contentType: "application/json; charset=utf-8"
                    ,dataType: "json"
                    ,success: function (data) {
                        $.ajax({
                            url: "Services/User.svc/insertRelUserRol"
                            , type: "POST"
                            , dataType: "json"
                            , data: '{"ID_USER":' + idUser + ',"ROLES":"' + check + '"}'
                            , contentType: "application/json; charset=utf-8"
                            , success: function (data){
                                console.log('Relación creada');
                                console.log(idUser + check);
                            }
                            , error: function (result) {
                                console.log('Error al crear la relación ' + result.status + ' ' + result.statusText);
                            }
                        });
                        that.reloadUserDataTable();
                        return true;
                    }
                    ,error: function (result) {
                        alert('Error al modificar usuario' + result.status + ' ' + result.statusText);
                    }
                });
            }
        }
    });
    return this.dialogModificarUsuario;
} //Fin dialog modificar usuario

imc.ui.UserPage.prototype.clickBtnNewUser = function () {
};

imc.ui.UserPage.prototype.clickBtnDeleteUser = function () {
};

imc.ui.UserPage.prototype.clickBtnRow = function () {
};